package main

import (
	"LterServer/model"
	"LterServer/pkt"
	"LterServer/util"
	"flag"
	"fmt"
	"net"
	"net/http"
	_ "net/http/pprof"
	"strconv"
	"time"

	"gitee.com/konyshe/gogo"
)

var (
	M_RECV_PORT = 21206
	M_PCAP_FILE string
	M_LIST_MODE = false
	M_DEBUG     = false
	M_VERSION   = false

	pProRePlayTask  *gogo.TaskModel
	pProPayloadTask *gogo.TaskModel
	pProPacketTask  *gogo.TaskModel

	//服务端serverPort和客户端的连接句柄
	pUDPConn *net.UDPConn
)

func main() {
	//先读取参数
	flag.StringVar(&M_PCAP_FILE, "read", M_PCAP_FILE, "pcap file name")
	flag.BoolVar(&M_LIST_MODE, "list", M_LIST_MODE, "list network device num")
	flag.BoolVar(&M_DEBUG, "debug", false, "run mode")
	flag.BoolVar(&M_VERSION, "version", false, "show version")

	flag.Parse()

	if M_VERSION {
		fmt.Println("1.1.6")
		return
	}

	if M_LIST_MODE { //是否只列出网卡清单就结束
		ListDevice()
		return
	}

	//启动性能评估
	cnPprofPort := util.ConfigGetPprofPort()
	if cnPprofPort > 0 {
		go http.ListenAndServe(":"+strconv.Itoa(cnPprofPort), nil)
	}

	mMaxQueue := util.ConfigGetMaxQueue()

	//启动转发报文
	mOutDeviceNum := util.ConfigGetOutDeviceNum()
	if mOutDeviceNum > 0 {
		pProRePlayTask = gogo.NewTask(pkt.NewProRePlay(mOutDeviceNum), mMaxQueue)
	}

	if M_PCAP_FILE == "" { //是否获取pUDPConn，以便UDP模式下响应心跳包
		mInDeviceNum := util.ConfigGetInDeviceNum()
		mMaxMTU := util.ConfigGetMaxMTU()

		if mInDeviceNum > 0 {
			go LoadFromDevice(M_RECV_PORT, mInDeviceNum, mMaxMTU)

		} else {
			pUDPConn = LoadFromUDP(M_RECV_PORT, mMaxMTU)
		}
	}

	//启动数据预处理
	pProPayloadTask = gogo.NewTask(NewProPayload(pUDPConn, M_DEBUG), mMaxQueue)

	//启动协议还原，目前还在测试阶段，因此只在DEBUG模式下启动
	if M_DEBUG {
		//pProPacketTask = gogo.NewTask(pkt.NewProPacket(), mMaxQueue)
	}

	//初始化上网手机号管理
	model.InitLterPhone()

	//初始化空口设备管理
	model.InitLterClient()

	//初始化IP地址库
	util.InitIPRegion()

	//初始化服务器的健康状态
	util.InitHealth()

	if M_PCAP_FILE != "" { //优先判断读报模式
		LoadFromPcap(M_PCAP_FILE)

	} else {
		if M_DEBUG {
			model.AddLterClientInfo("118.25.102.221:21306", time.Now())
			model.AddLterClientInfo("118.25.102.227:21306", time.Now())

			model.UpLterPhoneInfo(13005996130, "118.25.102.221:21306", 112233445566, 1, 10356)
			model.UpLterPhoneInfo(17183375111, "118.25.102.227:21306", 117755119988, 1, 977)
			model.UpLterPhoneInfo(18994000152, "118.25.102.221:21306", 998855119977, 1, 1587)

		} else {
			go func() {
				for { //定期发送一个空包给数据预处理，方便没有数据的确情况下，保证数据预处理的自我检测定期执行
					time.Sleep(time.Duration(1) * time.Second)
					pProPayloadTask.Push(&ProPayloadData{nil, 0, nil})
				}
			}()
		}

		//ControlWebStart(cnControlPort)
	}

	gogo.GlobalSignalWait()
}
